package com.example.financeapi.config.wechat;

import com.alibaba.fastjson.JSONObject;
import com.example.financeapi.config.constant.APIConstant;
import com.example.financeapi.config.wechat.mp.WxMpProperties;
import com.example.financeapi.utils.HttpUtil;
import com.example.financeapi.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class WechatMsg {

    @Autowired
    private RedisUtils strRedis;
    @Autowired
    private WxMpProperties wxMpProperties;

    /**
     * 获取微信 access_token
     * @return token
     */
    public String getToken(){
        String getMyAppId =wxMpProperties.getConfigs().get(0).getAppId();
        String getMyAppSecret =wxMpProperties.getConfigs().get(0).getSecret();
        String getToken =strRedis.get("mp_access_token-"+getMyAppId);
        if(StringUtils.isEmpty(getToken)){
            String getTokenApi = String.format(APIConstant.MX_ACCESS_TOKEN_URL,getMyAppId,getMyAppSecret);
            String tokenJsonStr = HttpUtil.doGetPost(getTokenApi,"GET",null);
            JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
            getToken = (String) tokenJson.get("access_token");
            strRedis.set("mp_access_token-"+getMyAppId,getToken, APIConstant.TOKEN_TIMES);
        }
        return getToken;
    }

    /***
     * 发送自定义模板消息
     * @param data json参数
     * @return
     */
    public boolean sendWeChatMsg(String data){
        String token =getToken();
        if(StringUtils.isBlank(token)){
            log.info("token为空,获取token失败！token={}",token);
            return false;
        }
        //发送微信消息地址
        String sendMsgApi = String.format(APIConstant.SEND_WECHATMSG_URL,token);
        if(StringUtils.isEmpty(data)){
            log.info("模版参数为空！data={}",data);
            return false;
        }
        String resultJson =HttpUtil.sendHttpGetPost(sendMsgApi,"POST",data);
        JSONObject sendMsgJson = JSONObject.parseObject(resultJson);
        if(sendMsgJson!=null){
            if("0".equals(sendMsgJson.getString("errcode"))){
                log.info("【SendWeChatMsg】发送模板消息成功！data={},sendMsgJson={}",data,sendMsgJson);
            }else{
                log.info("【SendWeChatMsg】发送模板消息失败！code={},data={},sendMsgJson={}",sendMsgJson.getString("errcode"),data,sendMsgJson);
                return false;
            }
        }
        return true;
    }

}
